#!/bin/bash

#设置日志文件存放目录
logs_dir="/usr/local/nginx/logs"

store_dir="/data/backup/nginx/logs"

# 设置nginx reload命令，reload才会释放文件句柄，不然就会一直写到mv之后的日志文件
nginx_reopen="/usr/local/nginx/sbin/nginx -s reopen "

# 设置日期格式
date_format=$(date -d "-1 hours" +%Y_%m_%d_%H)
year_format=$(echo $date_format | awk -F '_' '{print $1}')
month_format=$(echo $date_format | awk -F '_' '{print $2}')
day_format=$(echo $date_format | awk -F '_' '{print $3}')
hour_format=$(echo $date_format | awk -F '_' '{print $4}')

dist_dir=${store_dir}/${year_format}/${month_format}/${day_format}
mkdir -p ${dist_dir}
for i in $(ls ${logs_dir}/*.log); do
    dist_file=${dist_dir}/$(basename ${i})_${date_format}
    count=0
    while :; do
        if [ ! -f "${dist_file}" ]; then
            break
        fi
        dist_file=${dist_dir}/$(basename ${i})_${date_format}.${count}
        let count=count+1
    done
    mv $i ${dist_file}
done
eval $nginx_reopen
